{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "9ef9223b",
   "metadata": {},
   "source": [
    "# 2-3,动态计算图"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "75a2ed0e",
   "metadata": {},
   "source": [
    "本节我们将介绍 Pytorch的动态计算图。\n",
    "\n",
    "包括： \n",
    "\n",
    "* 动态计算图简介\n",
    "\n",
    "* 计算图中的Function\n",
    "\n",
    "* 计算图和反向传播\n",
    "\n",
    "* 叶子节点和非叶子节点\n",
    "\n",
    "* 计算图在TensorBoard中的可视化\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e1bea930",
   "metadata": {},
   "source": [
    "### 一，动态计算图简介"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b4060600",
   "metadata": {},
   "source": [
    "![](./data/torch动态图.gif)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d0ec87d8",
   "metadata": {},
   "source": [
    "Pytorch的计算图由节点和边组成，节点表示张量或者Function，边表示张量和Function之间的依赖关系。\n",
    "\n",
    "Pytorch中的计算图是动态图。这里的动态主要有两重含义。\n",
    "\n",
    "第一层含义是：计算图的正向传播是立即执行的。无需等待完整的计算图创建完毕，每条语句都会在计算图中动态添加节点和边，并立即执行正向传播得到计算结果。\n",
    "\n",
    "第二层含义是：计算图在反向传播后立即销毁。下次调用需要重新构建计算图。如果在程序中使用了backward方法执行了反向传播，或者利用torch.autograd.grad方法计算了梯度，那么创建的计算图会被立即销毁，释放存储空间，下次调用需要重新创建。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1b222f91",
   "metadata": {},
   "source": [
    "**1，计算图的正向传播是立即执行的。**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b4663b84",
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch \n",
    "w = torch.tensor([[3.0,1.0]],requires_grad=True)\n",
    "b = torch.tensor([[3.0]],requires_grad=True)\n",
    "X = torch.randn(10,2)\n",
    "Y = torch.randn(10,1)\n",
    "Y_hat = X@w.t() + b  # Y_hat定义后其正向传播被立即执行，与其后面的loss创建语句无关\n",
    "loss = torch.mean(torch.pow(Y_hat-Y,2))\n",
    "\n",
    "print(loss.data)\n",
    "print(Y_hat.data)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d1907e4f",
   "metadata": {},
   "source": [
    "```\n",
    "tensor(17.8969)\n",
    "tensor([[3.2613],\n",
    "        [4.7322],\n",
    "        [4.5037],\n",
    "        [7.5899],\n",
    "        [7.0973],\n",
    "        [1.3287],\n",
    "        [6.1473],\n",
    "        [1.3492],\n",
    "        [1.3911],\n",
    "        [1.2150]])\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "26be8027",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "2fa2fd5c",
   "metadata": {},
   "source": [
    "**2，计算图在反向传播后立即销毁。**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "567ce1d0",
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch \n",
    "w = torch.tensor([[3.0,1.0]],requires_grad=True)\n",
    "b = torch.tensor([[3.0]],requires_grad=True)\n",
    "X = torch.randn(10,2)\n",
    "Y = torch.randn(10,1)\n",
    "Y_hat = X@w.t() + b  # Y_hat定义后其正向传播被立即执行，与其后面的loss创建语句无关\n",
    "loss = torch.mean(torch.pow(Y_hat-Y,2))\n",
    "\n",
    "#计算图在反向传播后立即销毁，如果需要保留计算图, 需要设置retain_graph = True\n",
    "loss.backward()  #loss.backward(retain_graph = True) \n",
    "\n",
    "#loss.backward() #如果再次执行反向传播将报错\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "74f0bf17",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "6611afc1",
   "metadata": {},
   "source": [
    "### 二，计算图中的Function"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "04cce9f5",
   "metadata": {},
   "source": [
    "计算图中的 张量我们已经比较熟悉了, 计算图中的另外一种节点是Function, 实际上就是 Pytorch中各种对张量操作的函数。\n",
    "\n",
    "这些Function和我们Python中的函数有一个较大的区别，那就是它同时包括正向计算逻辑和反向传播的逻辑。\n",
    "\n",
    "我们可以通过继承torch.autograd.Function来创建这种支持反向传播的Function\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "eb1b41f0",
   "metadata": {},
   "outputs": [],
   "source": [
    "class MyReLU(torch.autograd.Function):\n",
    "   \n",
    "    #正向传播逻辑，可以用ctx存储一些值，供反向传播使用。\n",
    "    @staticmethod\n",
    "    def forward(ctx, input):\n",
    "        ctx.save_for_backward(input)\n",
    "        return input.clamp(min=0)\n",
    "\n",
    "    #反向传播逻辑\n",
    "    @staticmethod\n",
    "    def backward(ctx, grad_output):\n",
    "        input, = ctx.saved_tensors\n",
    "        grad_input = grad_output.clone()\n",
    "        grad_input[input < 0] = 0\n",
    "        return grad_input\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "090a5095",
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch \n",
    "w = torch.tensor([[3.0,1.0]],requires_grad=True)\n",
    "b = torch.tensor([[3.0]],requires_grad=True)\n",
    "X = torch.tensor([[-1.0,-1.0],[1.0,1.0]])\n",
    "Y = torch.tensor([[2.0,3.0]])\n",
    "\n",
    "relu = MyReLU.apply # relu现在也可以具有正向传播和反向传播功能\n",
    "Y_hat = relu(X@w.t() + b)\n",
    "loss = torch.mean(torch.pow(Y_hat-Y,2))\n",
    "\n",
    "loss.backward()\n",
    "\n",
    "print(w.grad)\n",
    "print(b.grad)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "af3e5a75",
   "metadata": {},
   "source": [
    "```\n",
    "tensor([[4.5000, 4.5000]])\n",
    "tensor([[4.5000]])\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9f0bf02b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Y_hat的梯度函数即是我们自己所定义的 MyReLU.backward\n",
    "\n",
    "print(Y_hat.grad_fn)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d3caa97a",
   "metadata": {},
   "source": [
    "```\n",
    "<torch.autograd.function.MyReLUBackward object at 0x1205a46c8>\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a66dd09b",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "5ca01eba",
   "metadata": {},
   "source": [
    "### 三，计算图与反向传播"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b03feb55",
   "metadata": {},
   "source": [
    "了解了Function的功能，我们可以简单地理解一下反向传播的原理和过程。理解该部分原理需要一些高等数学中求导链式法则的基础知识。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1dab19a6",
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch \n",
    "\n",
    "x = torch.tensor(3.0,requires_grad=True)\n",
    "y1 = x + 1\n",
    "y2 = 2*x\n",
    "loss = (y1-y2)**2\n",
    "\n",
    "loss.backward()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b44a57b2",
   "metadata": {},
   "source": [
    "loss.backward()语句调用后，依次发生以下计算过程。\n",
    "\n",
    "1，loss自己的grad梯度赋值为1，即对自身的梯度为1。\n",
    "\n",
    "2，loss根据其自身梯度以及关联的backward方法，计算出其对应的自变量即y1和y2的梯度，将该值赋值到y1.grad和y2.grad。\n",
    "\n",
    "3，y2和y1根据其自身梯度以及关联的backward方法, 分别计算出其对应的自变量x的梯度，x.grad将其收到的多个梯度值累加。\n",
    "\n",
    "（注意，1,2,3步骤的求梯度顺序和对多个梯度值的累加规则恰好是求导链式法则的程序表述）\n",
    "\n",
    "正因为求导链式法则衍生的梯度累加规则，张量的grad梯度不会自动清零，在需要的时候需要手动置零。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8c3f8d7c",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "971b2a12",
   "metadata": {},
   "source": [
    "### 四，叶子节点和非叶子节点"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "63b9d349",
   "metadata": {},
   "source": [
    "执行下面代码，我们会发现 loss.grad并不是我们期望的1,而是 None。\n",
    "\n",
    "类似地 y1.grad 以及 y2.grad也是 None.\n",
    "\n",
    "这是为什么呢？这是由于它们不是叶子节点张量。\n",
    "\n",
    "在反向传播过程中，只有 is_leaf=True 的叶子节点，需要求导的张量的导数结果才会被最后保留下来。\n",
    "\n",
    "那么什么是叶子节点张量呢？叶子节点张量需要满足两个条件。\n",
    "\n",
    "1，叶子节点张量是由用户直接创建的张量，而非由某个Function通过计算得到的张量。\n",
    "\n",
    "2，叶子节点张量的 requires_grad属性必须为True.\n",
    "\n",
    "Pytorch设计这样的规则主要是为了节约内存或者显存空间，因为几乎所有的时候，用户只会关心他自己直接创建的张量的梯度。\n",
    "\n",
    "所有依赖于叶子节点张量的张量, 其requires_grad 属性必定是True的，但其梯度值只在计算过程中被用到，不会最终存储到grad属性中。\n",
    "\n",
    "如果需要保留中间计算结果的梯度到grad属性中，可以使用 retain_grad方法。\n",
    "如果仅仅是为了调试代码查看梯度值，可以利用register_hook打印日志。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f5edd627",
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch \n",
    "\n",
    "x = torch.tensor(3.0,requires_grad=True)\n",
    "y1 = x + 1\n",
    "y2 = 2*x\n",
    "loss = (y1-y2)**2\n",
    "\n",
    "loss.backward()\n",
    "print(\"loss.grad:\", loss.grad)\n",
    "print(\"y1.grad:\", y1.grad)\n",
    "print(\"y2.grad:\", y2.grad)\n",
    "print(x.grad)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0c69ad53",
   "metadata": {},
   "source": [
    "```\n",
    "loss.grad: None\n",
    "y1.grad: None\n",
    "y2.grad: None\n",
    "tensor(4.)\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "395f5d8b",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(x.is_leaf)\n",
    "print(y1.is_leaf)\n",
    "print(y2.is_leaf)\n",
    "print(loss.is_leaf)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a13c7f76",
   "metadata": {},
   "source": [
    "```\n",
    "True\n",
    "False\n",
    "False\n",
    "False\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e3ca6499",
   "metadata": {},
   "source": [
    "利用retain_grad可以保留非叶子节点的梯度值，利用register_hook可以查看非叶子节点的梯度值。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e3c9243c",
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch \n",
    "\n",
    "#正向传播\n",
    "x = torch.tensor(3.0,requires_grad=True)\n",
    "y1 = x + 1\n",
    "y2 = 2*x\n",
    "loss = (y1-y2)**2\n",
    "\n",
    "#非叶子节点梯度显示控制\n",
    "y1.register_hook(lambda grad: print('y1 grad: ', grad))\n",
    "y2.register_hook(lambda grad: print('y2 grad: ', grad))\n",
    "loss.retain_grad()\n",
    "\n",
    "#反向传播\n",
    "loss.backward()\n",
    "print(\"loss.grad:\", loss.grad)\n",
    "print(\"x.grad:\", x.grad)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d6907ea0",
   "metadata": {},
   "source": [
    "```\n",
    "y2 grad:  tensor(4.)\n",
    "y1 grad:  tensor(-4.)\n",
    "loss.grad: tensor(1.)\n",
    "x.grad: tensor(4.)\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a9b7699c",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "eece20b2",
   "metadata": {},
   "source": [
    "### 五，计算图在TensorBoard中的可视化"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f2f6a109",
   "metadata": {},
   "source": [
    "可以利用 torch.utils.tensorboard 将计算图导出到 TensorBoard进行可视化。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d39ce53a",
   "metadata": {},
   "outputs": [],
   "source": [
    "from torch import nn \n",
    "class Net(nn.Module):\n",
    "    def __init__(self):\n",
    "        super(Net, self).__init__()\n",
    "        self.w = nn.Parameter(torch.randn(2,1))\n",
    "        self.b = nn.Parameter(torch.zeros(1,1))\n",
    "\n",
    "    def forward(self, x):\n",
    "        y = x@self.w + self.b\n",
    "        return y\n",
    "\n",
    "net = Net()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f8bf8db1",
   "metadata": {},
   "outputs": [],
   "source": [
    "from torch.utils.tensorboard import SummaryWriter\n",
    "writer = SummaryWriter('./data/tensorboard')\n",
    "writer.add_graph(net,input_to_model = torch.rand(10,2))\n",
    "writer.close()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a2452b7a",
   "metadata": {},
   "outputs": [],
   "source": [
    "%load_ext tensorboard\n",
    "#%tensorboard --logdir ./data/tensorboard\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4756a1ab",
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensorboard import notebook\n",
    "notebook.list() \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c4953924",
   "metadata": {},
   "outputs": [],
   "source": [
    "#在tensorboard中查看模型\n",
    "notebook.start(\"--logdir ./data/tensorboard\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e1d32759",
   "metadata": {},
   "source": [
    "![](./data/2-3-计算图可视化.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "03cce56c",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "36351f46",
   "metadata": {},
   "source": [
    "**如果本书对你有所帮助，想鼓励一下作者，记得给本项目加一颗星星star⭐️，并分享给你的朋友们喔😊!** \n",
    "\n",
    "如果对本书内容理解上有需要进一步和作者交流的地方，欢迎在公众号\"算法美食屋\"下留言。作者时间和精力有限，会酌情予以回复。\n",
    "\n",
    "也可以在公众号后台回复关键字：**加群**，加入读者交流群和大家讨论。\n",
    "\n",
    "![算法美食屋logo.png](https://tva1.sinaimg.cn/large/e6c9d24egy1h41m2zugguj20k00b9q46.jpg)"
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "cell_metadata_filter": "-all",
   "formats": "ipynb,md",
   "main_language": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
